package restdom.ruleengine;

import javax.rules.RuleServiceProvider;

import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springmodules.jsr94.rulesource.DefaultRuleSource;
import org.springmodules.jsr94.rulesource.RuleSource;

public class DefaultRuleSourceResolver implements RuleSourceResolver {

	private static final String DEFAULT_SUFFIX = ".drl";

	private String suffix = DEFAULT_SUFFIX;

	private RuleServiceProvider ruleServiceProvider;

	public RuleSource resolveRuleSource(String bindUri, String source,
			Class clazz) throws Exception {
		if (!StringUtils.hasText(source)) {
			source = ClassUtils.addResourcePathToPackagePath(clazz, clazz
					.getSimpleName()
					+ getSuffix());
		}
		return createRuleSource(bindUri, source);
	}

	protected RuleSource createRuleSource(String bindUri, String source)
			throws Exception {
		DefaultRuleSource ruleSource = new DefaultRuleSource();
		ruleSource.setBindUri(bindUri);
		ruleSource.setRuleServiceProvider(ruleServiceProvider);
		ruleSource.setSource(new ClassPathResource(source));

		ruleSource.afterPropertiesSet();

		return ruleSource;
	}

	public String getSuffix() {
		return suffix;
	}

	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}

	public RuleServiceProvider getRuleServiceProvider() {
		return ruleServiceProvider;
	}

	public void setRuleServiceProvider(RuleServiceProvider ruleServiceProvider) {
		this.ruleServiceProvider = ruleServiceProvider;
	}
}
